package users

import (
	"encoding/json"
	"fmt"
	"github.com/bitly/go-simplejson"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"net/http"
	"tao-admin/utils"
	"time"
)

var (
	Secret     = "aibot"   // 加盐
	ExpireTime = 3600 * 24 // token有效期
)

type UserView struct {
	UserService *UserService
}

func NewUserView() *UserView {
	return &UserView{
		UserService: NewUserService(),
	}
}

func (view *UserView) searchUserInfoView(ctx *gin.Context) {
	res := utils.NewSimpleRes()
	condition := &SearchUserCondition{}
	list, total, err := view.UserService.GetUserInfos(ctx, condition)
	if err != nil {
		resp := fmt.Sprintf("error:%v", err)
		res.Retcode = -1
		res.Message = "failed"
		res.Data = map[string]interface{}{
			"err": err,
			"msg": resp,
		}
	} else {
		res.Data = map[string]interface{}{
			"items": list,
			"total": total,
		}
	}
	ctx.JSON(200, res)
}

func (view *UserView) createUserInfoView(ctx *gin.Context) {
	res := utils.NewSimpleRes()
	err, msg := view.UserService.CreateUserItem(ctx)
	if err != nil || msg != "" {
		res.Retcode = -1
		res.Message = "failed"
		res.Data = map[string]interface{}{
			"err": err,
			"msg": msg,
		}
	}
	ctx.JSON(200, res)
}

func (view *UserView) updateUserInfoView(ctx *gin.Context) {
	res := utils.NewSimpleRes()
	err, msg := view.UserService.UpdateUserItem(ctx)
	if err != nil || msg != "" {
		res.Retcode = -1
		res.Message = "failed"
		res.Data = map[string]interface{}{
			"err": err,
			"msg": msg,
		}
	}
	ctx.JSON(200, res)
}

func (view *UserView) userLoginView(ctx *gin.Context) {
	rData, _ := ioutil.ReadAll(ctx.Request.Body)
	sParaJson, err := simplejson.NewJson(rData)

	username, err1 := sParaJson.Get("username").String()
	password, err2 := sParaJson.Get("password").String()
	if err1 != nil || err2 != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"retcode": -1,
			"data":    nil,
			"message": "必传参数未填！",
		})
	}
	condition := &SearchUserCondition{
		Username: &username,
	}
	list, _, err := view.UserService.GetUserInfos(ctx, condition)
	log.Println(list)
	if len(list) == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"retcode": -1,
			"data":    nil,
			"message": "用户不存在",
		})
		return
	}
	user := list[0]
	err, _ = view.UserService.HandleLogin(user)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"retcode": -1,
			"data":    nil,
			"message": err,
		})
		return
	}

	// 获取token
	claims := &utils.JWTClaims{
		Username: username,
		Password: password,
	}
	claims.IssuedAt = time.Now().Unix()
	claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(ExpireTime)).Unix()
	signedToken, err := utils.GetToken(claims)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"retcode": -1,
			"data":    nil,
			"message": err,
		})
		return
	}

	//把用户名传回去，前端保存
	data := Data{AccessToken: signedToken, UserInfo: UserInfo{
		Username: username,
		ImgUrl:   *user.ImgUrl,
		Email:    *user.Email,
	}}
	resp := Response{Code: 20000, Data: data}
	byteArray, err := json.Marshal(resp)
	if err != nil {
		fmt.Println(err)
	}
	log.Println("登录成功")
	fmt.Println(string(byteArray))

	ctx.JSON(http.StatusOK, resp)
}

func (view *UserView) userLogoutView(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
}

func (view *UserView) getUserView(ctx *gin.Context) {
	res := utils.NewSimpleRes()

	rData, _ := ioutil.ReadAll(ctx.Request.Body)
	sParaJson, err := simplejson.NewJson(rData)
	username, err := sParaJson.Get("username").String()
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"retcode": -1,
			"data":    nil,
			"message": "必传参数username！",
		})
	}

	condition := &SearchUserCondition{
		Username: &username,
	}
	list, _, err := view.UserService.GetUserInfos(ctx, condition)
	if err != nil {
		resp := fmt.Sprintf("error:%v", err)
		res.Retcode = -1
		res.Message = "failed"
		res.Data = map[string]interface{}{
			"err": err,
			"msg": resp,
		}
	} else {
		res.Data = map[string]interface{}{
			"user": list[0],
		}
	}
	ctx.JSON(200, res)
}

func (view *UserView) getTestView(ctx *gin.Context) {
	ctx.JSON(200, gin.H{
		"status": 0,
		"msg":    "get success",
		"data":   "get success",
	})
}

func (view *UserView) postTestView(ctx *gin.Context) {

	log.Println("访问登录接口, payload信息:", ctx.Request)
	log.Println("body:", ctx.Request.Body)

	// post接口，获取body payload
	rData, _ := ioutil.ReadAll(ctx.Request.Body)
	sParaJson, err := simplejson.NewJson(rData)
	log.Println("sParaJson:", sParaJson)

	postdata, err := sParaJson.Get("postdata").String()
	if err != nil {
		ctx.JSON(200, gin.H{
			"status": -1,
			"msg":    "post failed",
			"data":   "出错!",
		})
	}

	ctx.JSON(200, gin.H{
		"status": 0,
		"msg":    "post success",
		"data":   fmt.Sprintf("your post data: %v", postdata),
	})
}
